package com.tjec.project.businessWorkbench.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.tjec.common.utils.DateUtils;
import com.tjec.common.utils.ServletUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.framework.security.service.TokenService;
import com.tjec.framework.web.domain.TreeSelect;
import com.tjec.framework.web.domain.TreeSelectExport;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tjec.project.businessWorkbench.mapper.BmsBusinessTaskMapper;
import com.tjec.project.businessWorkbench.domain.BmsBusinessTask;
import com.tjec.project.businessWorkbench.domain.BmsProjectDocCatalog;
import com.tjec.project.businessWorkbench.domain.ImportBmsBusinessTask;
import com.tjec.project.businessWorkbench.dto.BmsTaskTimerDto;
import com.tjec.project.businessWorkbench.service.IBmsBusinessTaskService;
import com.tjec.project.system.domain.BmsMdBusinessCategory;

/**
 * 任务管理Service业务层处理
 * 
 * @author pangyongfeng
 * @date 2020-04-22
 */
@Service
public class BmsBusinessTaskServiceImpl implements IBmsBusinessTaskService {
	@Autowired
	private BmsBusinessTaskMapper bmsBusinessTaskMapper;

	@Autowired
	private TokenService tokenService;

	/**
	 * 查询任务管理
	 * 
	 * @param guid 任务管理ID
	 * @return 任务管理
	 */
	@Override
	public BmsBusinessTask selectBmsBusinessTaskByGuid(String id) {
		return bmsBusinessTaskMapper.selectBmsBusinessTaskByGuid(id);
	}

	/**
	 * 查询任务管理列表
	 * 
	 * @param bmsBusinessTask 任务管理
	 * @return 任务管理
	 */
	@Override
	public List<BmsBusinessTask> selectBmsBusinessTaskList(BmsBusinessTask bmsBusinessTask) {
		return bmsBusinessTaskMapper.selectBmsBusinessTaskList(bmsBusinessTask);
	}

	/**
	 * 新增任务管理
	 * 
	 * @param bmsBusinessTask 任务管理
	 * @return 结果
	 */
	@Override
	public int insertBmsBusinessTask(BmsBusinessTask bmsBusinessTask) {
		return bmsBusinessTaskMapper.insertBmsBusinessTask(bmsBusinessTask);
	}

	/**
	 * 修改任务管理
	 * 
	 * @param bmsBusinessTask 任务管理
	 * @return 结果
	 */
	@Override
	public int updateBmsBusinessTask(BmsBusinessTask bmsBusinessTask) {
		bmsBusinessTask.setUpdateTime(DateUtils.getNowDate());
		return bmsBusinessTaskMapper.updateBmsBusinessTask(bmsBusinessTask);
	}

	/**
	 * 批量删除任务管理
	 * 
	 * @param ids 需要删除的任务管理ID
	 * @return 结果
	 */
	@Override
	public int deleteBmsBusinessTaskByGuids(String[] guids) {
		return bmsBusinessTaskMapper.deleteBmsBusinessTaskByGuids(guids);
	}

	/**
	 * 删除任务管理信息
	 * 
	 * @param id 任务管理ID
	 * @return 结果
	 */
	@Override
	public int deleteBmsBusinessTaskByGuid(String guid) {
		return bmsBusinessTaskMapper.deleteBmsBusinessTaskByGuid(guid);
	}

	@Override
	public List<TreeSelect> buildTaskTreeSelect(List<BmsBusinessTask> bmsBusinessTasks) {
		List<BmsBusinessTask> taskTrees = buildTaskTree(bmsBusinessTasks);
		return taskTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
	}

	@Override
	public List<BmsBusinessTask> buildTaskTree(List<BmsBusinessTask> bmsBusinessTasks) {
		List<BmsBusinessTask> returnList = new ArrayList<BmsBusinessTask>();
		List<String> tempList = new ArrayList<String>();
		for (BmsBusinessTask bmsBusinessTask : bmsBusinessTasks) {
			tempList.add(bmsBusinessTask.getGuid());
		}
		for (Iterator<BmsBusinessTask> iterator = bmsBusinessTasks.iterator(); iterator.hasNext();) {
			BmsBusinessTask taskType = (BmsBusinessTask) iterator.next();
			// 如果是顶级节点, 遍历该父节点的所有子节点
			if (!tempList.contains(taskType.getTaskParentId())) {
				recursionFn(bmsBusinessTasks, taskType);
				returnList.add(taskType);
			}
		}
		if (returnList.isEmpty()) {
			returnList = bmsBusinessTasks;
		}
		return returnList;
	}

	/**
	 * 递归列表
	 */
	private void recursionFn(List<BmsBusinessTask> list, BmsBusinessTask t) {
		// 得到子节点列表
		List<BmsBusinessTask> childList = getChildList(list, t);
		t.setChildren(childList);
		for (BmsBusinessTask tChild : childList) {
			if (hasChild(list, tChild)) {
				// 判断是否有子节点
				Iterator<BmsBusinessTask> it = childList.iterator();
				while (it.hasNext()) {
					BmsBusinessTask n = (BmsBusinessTask) it.next();
					recursionFn(list, n);
				}
			}
		}
	}

	/**
	 * 得到子节点列表
	 */
	private List<BmsBusinessTask> getChildList(List<BmsBusinessTask> list, BmsBusinessTask t) {
		List<BmsBusinessTask> tlist = new ArrayList<BmsBusinessTask>();
		Iterator<BmsBusinessTask> it = list.iterator();
		while (it.hasNext()) {
			BmsBusinessTask n = (BmsBusinessTask) it.next();
			if (StringUtils.isNotNull(n.getTaskParentId()) && t.getGuid().equals(n.getTaskParentId())) {
				tlist.add(n);
			}
		}
		return tlist;
	}

	/**
	 * 判断是否有子节点
	 */
	private boolean hasChild(List<BmsBusinessTask> list, BmsBusinessTask t) {
		return getChildList(list, t).size() > 0 ? true : false;
	}

	@Override
	public List<BmsBusinessTask> exportBmsBusinessTaskList(BmsBusinessTask bmsBusinessTask) {
		return bmsBusinessTaskMapper.exportBmsBusinessTaskList(bmsBusinessTask);
	}

	public void insertBmsBusinessTask(List<TreeSelectExport> items, TreeSelectExport item, String guid,
			String createBy) {

		if (items != null && items.size() > 0) {
			items.forEach(it -> {
				BmsBusinessTask bmsBusinessTask = new BmsBusinessTask();
				bmsBusinessTask.setName(it.getLabel());
				bmsBusinessTask.setBusinessId(it.getBusinessId());
				bmsBusinessTask.setTaskParentId(guid);
				bmsBusinessTask.setCreateBy(createBy);
				bmsBusinessTaskMapper.insertBmsBusinessTask(bmsBusinessTask);

				if (it.getChildren() != null && it.getChildren().size() > 0) {
					insertBmsBusinessTask(it.getChildren(), it, bmsBusinessTask.getGuid(), createBy);
				}
			});
		}

	}

	@Override
	public int importBmsBusinessTasksList(List<BmsBusinessTask> bmsBusinessTasks) {
		String createBy = tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId();
		List<BmsBusinessTask> bmsBusinessTaskTrees = buildTaskTreeExport(bmsBusinessTasks);

		List<TreeSelectExport> res = bmsBusinessTaskTrees.stream().map(TreeSelectExport::new)
				.collect(Collectors.toList());

		if (res != null && res.size() > 0) {
			res.forEach(item -> {
				BmsBusinessTask bmsBusinessTask = new BmsBusinessTask();
				bmsBusinessTask.setName(item.getLabel());
				bmsBusinessTask.setBusinessId(item.getBusinessId());
				bmsBusinessTask.setTaskParentId("0");
				bmsBusinessTask.setCreateBy(createBy);
				bmsBusinessTaskMapper.insertBmsBusinessTask(bmsBusinessTask);
				if (item.getChildren() != null && item.getChildren().size() > 0) {
					insertBmsBusinessTask(item.getChildren(), item, bmsBusinessTask.getGuid(), createBy);
				}
			});
		}
		return 1;
	}

	public List<BmsBusinessTask> buildTaskTreeExport(List<BmsBusinessTask> bmsBusinessTasks) {
		List<BmsBusinessTask> returnList = new ArrayList<BmsBusinessTask>();
		List<String> tempList = new ArrayList<String>();
		for (BmsBusinessTask bmsBusinessTask : bmsBusinessTasks) {
			tempList.add(bmsBusinessTask.getName());
		}
		for (Iterator<BmsBusinessTask> iterator = bmsBusinessTasks.iterator(); iterator.hasNext();) {
			BmsBusinessTask bmsBusinessTask = (BmsBusinessTask) iterator.next();
			// 如果是顶级节点, 遍历该父节点的所有子节点
			if (!tempList.contains(bmsBusinessTask.getParentName())) {
				recursionFnExport(bmsBusinessTasks, bmsBusinessTask);
				returnList.add(bmsBusinessTask);
			}
		}
		if (returnList.isEmpty()) {
			returnList = bmsBusinessTasks;
		}
		return returnList;
	}

	/**
	 * 递归列表
	 */
	private void recursionFnExport(List<BmsBusinessTask> list, BmsBusinessTask t) {
		// 得到子节点列表
		List<BmsBusinessTask> childList = getChildListExport(list, t);
		t.setChildren(childList);
		for (BmsBusinessTask tChild : childList) {
			if (hasChildExport(list, tChild)) {
				// 判断是否有子节点
				Iterator<BmsBusinessTask> it = childList.iterator();
				while (it.hasNext()) {
					BmsBusinessTask n = (BmsBusinessTask) it.next();
					recursionFnExport(list, n);
				}
			}
		}
	}

	/**
	 * 得到子节点列表
	 */
	private List<BmsBusinessTask> getChildListExport(List<BmsBusinessTask> list, BmsBusinessTask t) {
		List<BmsBusinessTask> tlist = new ArrayList<BmsBusinessTask>();
		Iterator<BmsBusinessTask> it = list.iterator();
		while (it.hasNext()) {
			BmsBusinessTask n = (BmsBusinessTask) it.next();
			if (StringUtils.isNotNull(n.getParentName()) && n.getParentName().equals(t.getName())) {
				tlist.add(n);
			}
		}
		return tlist;
	}

	/**
	 * 判断是否有子节点
	 */
	private boolean hasChildExport(List<BmsBusinessTask> list, BmsBusinessTask t) {
		return getChildList(list, t).size() > 0 ? true : false;
	}

	@Override
	public int importBmsBusinessTasks(List<ImportBmsBusinessTask> bmsBusinessTasks, String businessId) {
		Map<String, Object> parentTask = new HashMap<String, Object>();
		Map<String, Object> secondTask = new HashMap<String, Object>();

		int result = 0;
		// 保存一级任务
		for (ImportBmsBusinessTask importBmsBusinessTask : bmsBusinessTasks) {
			if (StringUtils.isNotBlank(importBmsBusinessTask.getFirstName())
					&& StringUtils.isBlank(importBmsBusinessTask.getSecondName())
					&& StringUtils.isBlank(importBmsBusinessTask.getThirdName())) {

				BmsBusinessTask bmsBusinessTask = new BmsBusinessTask();
				bmsBusinessTask.setName(importBmsBusinessTask.getFirstName());
				bmsBusinessTask.setCreateBy(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
				bmsBusinessTask.setMilestoneFlag(importBmsBusinessTask.getMilestoneFlag());
				bmsBusinessTask.setTaskParentId("0");
				bmsBusinessTask.setBusinessId(businessId);
				bmsBusinessTaskMapper.insertBmsBusinessTask(bmsBusinessTask);

				parentTask.put(importBmsBusinessTask.getFirstName(), bmsBusinessTask.getGuid());
			}
		}

		// 保存二级任务
		for (ImportBmsBusinessTask importBmsBusinessTask : bmsBusinessTasks) {
			if (!parentTask.isEmpty()) {
				if (StringUtils.isNotBlank(importBmsBusinessTask.getFirstName())
						&& StringUtils.isNotBlank(importBmsBusinessTask.getSecondName())
						&& StringUtils.isBlank(importBmsBusinessTask.getThirdName())) {

					if (parentTask.containsKey(importBmsBusinessTask.getFirstName())) {
						BmsBusinessTask bmsBusinessTask = new BmsBusinessTask();
						bmsBusinessTask.setName(importBmsBusinessTask.getSecondName());
						bmsBusinessTask.setCreateBy(
								tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
						bmsBusinessTask.setMilestoneFlag(importBmsBusinessTask.getMilestoneFlag());
						bmsBusinessTask
								.setTaskParentId(parentTask.get(importBmsBusinessTask.getFirstName()).toString());
						bmsBusinessTask.setBusinessId(businessId);

						bmsBusinessTaskMapper.insertBmsBusinessTask(bmsBusinessTask);

						secondTask.put(
								importBmsBusinessTask.getFirstName() + ";" + importBmsBusinessTask.getSecondName(),
								bmsBusinessTask.getGuid());
					}

				}
			}
		}

		// 保存三级任务
		for (ImportBmsBusinessTask importBmsBusinessTask : bmsBusinessTasks) {
			if (!secondTask.isEmpty()) {
				if (StringUtils.isNotBlank(importBmsBusinessTask.getFirstName())
						&& StringUtils.isNotBlank(importBmsBusinessTask.getSecondName())
						&& StringUtils.isNotBlank(importBmsBusinessTask.getThirdName())) {

					if (secondTask.containsKey(
							importBmsBusinessTask.getFirstName() + ";" + importBmsBusinessTask.getSecondName())) {
						BmsBusinessTask bmsBusinessTask = new BmsBusinessTask();
						bmsBusinessTask.setName(importBmsBusinessTask.getThirdName());
						bmsBusinessTask.setCreateBy(
								tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
						bmsBusinessTask.setMilestoneFlag(importBmsBusinessTask.getMilestoneFlag());
						bmsBusinessTask.setTaskParentId(secondTask
								.get(importBmsBusinessTask.getFirstName() + ";" + importBmsBusinessTask.getSecondName())
								.toString());
						bmsBusinessTask.setBusinessId(businessId);

						bmsBusinessTaskMapper.insertBmsBusinessTask(bmsBusinessTask);
					}

				}
			}
		}
		return result;
	}

	@Override
	public List<BmsBusinessTask> selectBmsBusinessTaskExportList(BmsBusinessTask bmsBusinessTask) {
		return bmsBusinessTaskMapper.selectBmsBusinessTaskExportList(bmsBusinessTask);
	}

	@Override
	public List<BmsTaskTimerDto> selectAllMsgTask() {
		return bmsBusinessTaskMapper.selectAllMsgTask();
	}

	@Override
	public int updateTaskCounts(BmsTaskTimerDto bmsTaskTimerDto) {
		return bmsBusinessTaskMapper.updateTaskCounts(bmsTaskTimerDto);
	}

}
